package org.lc.oauth.extension.handler;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.lc.oauth.dto.ErrorResult;
import org.lc.platform.base.enums.ResultCodeEnum;
import org.lc.platform.base.result.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

@Slf4j
public class AuthEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        log.info(String.valueOf(e));
        int code = ResultCodeEnum.FAILED.getCode();
        String msg = e.getMessage();
        var res = new ErrorResult(msg);
        code = res.getCode();
        msg = res.getMsg();
        var result = Result.error(code, msg);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
